package com.wgzx.modbus.idgen;

import com.wgzx.modbus.constant.ModbusConstants;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 此类线程安全
 *
 * @author gexin
 */
public class AtomicIdentifierGenerator implements IdentifierGenerator {

    private AtomicInteger cyclicalCounter = new AtomicInteger(0);

    /**
     * 递增的方式计算事务标识符
     *
     * @return int(0 ~ 65535)
     */
    @Override
    public int calculateTransactionIdentifier() {
        int currentId;
        int nextId;
        do {
            currentId = cyclicalCounter.get();
            nextId = (currentId + 1) % ModbusConstants.TRANSACTION_IDENTIFIER_MAX;
        } while (!cyclicalCounter.compareAndSet(currentId, nextId));

        return nextId;
    }
}
